package com.mtf.syncExportExcel.service.impl;

import com.alibaba.excel.write.metadata.WriteTable;
import com.mtf.syncExportExcel.entity.EasyExcelExport;
import com.mtf.syncExportExcel.entity.EasyExportEntity;
import com.mtf.syncExportExcel.entity.ExportConfigEntity;
import com.mtf.syncExportExcel.entity.ExportTaskEntity;
import com.mtf.syncExportExcel.handle.EasyExportExcelHandle;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class CommonExcelService {

    public <E, P> void easyExport(EasyExportEntity<E, P> exportBean) {
        //获取数据库的导出记录
        ExportTaskEntity exportTaskEntity = new ExportTaskEntity();
        //获取导出配置
        ExportConfigEntity config = new ExportConfigEntity();
        try {
            EasyExcelExport.<E, P>bulider()
                    .setClz(exportBean.getClz())
                    .setSheetName(exportBean.getSheetName())
                    .setPageSize(config.getPageSize())
                    .setMaxSheetLine(config.getMaxSheetLine())
                    .setLimitAllSheetLine(config.getLimitAllSheetLine())
                    .setExportHandle(new EasyExportExcelHandle<E, P>() {
                        //获取导出数据
                        public List<E> loadData(EasyExcelExport.ExportContext<E, P> context) {
                            return exportBean.getHandle().handle(context, exportTaskEntity);
                        }
                        @Override
                        public List<P> getPartition() {
                            return exportBean.getPartition();
                        }
                        public WriteTable getWriteTable() {
                            List<List<String>> header = exportBean.getHeader();
                            if (CollectionUtils.isEmpty(header)) {
                                return null;
                            }
                            WriteTable writeTable = new WriteTable();
                            writeTable.setTableNo(0);
                            writeTable.setHead(header);
                            return writeTable;
                        }
                        public void afterExportData(EasyExcelExport.ExportContext<E, P> context) { }
                    })
                    .create()
                    .export(exportBean.getFileName());
        } catch (Exception fe) {
            exportTaskEntity.setUpdateTime(new Date());
        }
    }

}
